<?php

namespace App\Service\WeChat;


class OpenWx
{
    protected $appid;
    protected $AppSecret;

    // 初始化操作
    public function __construct()
    {
        $this->appid     = 'wxa7eb0a3687ecf066';
        $this->AppSecret = '24f59339efb183edb7069f7133bc4900';
    }

    // 获取code

    // 获取


    // 获取个人信息:小程序登录
    public function getUserByMini($code)
    {
        $appid  = $this->appid; //appid
        $secret = $this->AppSecret;
        $url    = "https://api.weixin.qq.com/sns/jscode2session?appid=$appid&secret=$secret&js_code=$code&grant_type=authorization_code";
        $res    = $this->curl($url);
        //var_dump($url);
        //var_dump($res);
        //$logger = new LogFile();
        //$logger->write('Request | 微信小程序请求openID返回 |' . var_export($res, 1), 'info');

        //$data = json_decode($res, true);
        //$openid  = $data['openid'];
        //$session = $data['session_key'];

        return $res;
    }

    // 获取用户信息：app或公众号
    public function getUser($access_token, $openid)
    {
        $url  = 'https://api.weixin.qq.com/sns/userinfo?access_token='.$access_token.'&openid='.$openid.'&lang=zh_CN'; //获取用户信息的链接
        $res  = $this->curl($url);
        $user = json_decode($res, true); //将返回的json字符串转为数组

        return $res;
    }

    // 获取
    public function getAccessToken($code)
    {
        $appid  = $this->appid; //appid
        $secret = $this->AppSecret;
        $_url   = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid='.$appid.'&secret='.$secret.'&code='.$code.'&grant_type=authorization_code'; //获取access_token和openid的链接

        //$params = ['appid' => $this->appid, 'secret' => $this->AppSecret, 'js_code' => $code, 'grant_type' => 'authorization_code'];
        //$_url   = 'https://api.weixin.qq.com/sns/oauth2/access_token'; //获取access_token和openid的链接
        //$res    = $this->curl($_url, $params);

        $res    = $this->curl($_url);
        $data   = json_decode($res, true);
        $openid = $data['openid'];
        $_token = $data['access_token'];

        return $res;
    }


    // 生成微信登录的链接
    // $url 登录成功回调网址，请确保此地址跟公众号设置的授权回调页面路径一致  http://yourdomain.com/login.php
    public function makeUrlForCode($url)
    {
        $appid = $this->appid; //appid
        $_uri  = urlencode($url); //登录成功回调网址，请确保此地址跟公众号设置的授权回调页面路径一致。
        $scope = 'snsapi_userinfo'; //snsapi_base:只能获得用户的openid 或 snsapi_userinfo:可获得用户的基本信息
        $url   = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid='.$appid.'&redirect_uri='.$_uri.'&response_type=code&scope='.$scope.'&state=STATE#wechat_redirect';

        header('Location:'.$url);
        exit;
    }

    // 执行请求
    protected function curl2($url, $params = [], $expire = 0, $extend = array())
    {
        if(empty($url)){
            return array('code' => '100');
        }

        $_curl   = curl_init();
        $_header = array('Accept-Language: zh-CN', 'Connection: Keep-Alive', 'Cache-Control: no-cache',);
        // 只要第二个参数传了值之后，就是POST的
        if(!empty($params)){
            curl_setopt($_curl, CURLOPT_POSTFIELDS, ($params));
            curl_setopt($_curl, CURLOPT_POST, true);
        }
        curl_setopt($_curl, CURLOPT_HTTP09_ALLOWED, true);

        curl_setopt($_curl, CURLOPT_URL, $url);
        curl_setopt($_curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($_curl, CURLOPT_USERAGENT, 'API PHP CURL');
        curl_setopt($_curl, CURLOPT_HTTPHEADER, $_header);
        if($expire > 0){
            curl_setopt($_curl, CURLOPT_TIMEOUT, $expire); // 处理超时时间
            curl_setopt($_curl, CURLOPT_CONNECTTIMEOUT, $expire); // 建立连接超时时间
        }

        // 额外的配置
        if(!empty($extend)){
            curl_setopt_array($_curl, $extend);
        }

        // 执行结果 获取
        $result['result'] = curl_exec($_curl);
        var_dump($result['result']);


        $result['code']   = curl_getinfo($_curl, CURLINFO_HTTP_CODE);
        $result['info']   = curl_getinfo($_curl);
        if($result['result'] === false){
            $result['result'] = curl_error($_curl);
            $result['code']   = -curl_errno($_curl);
        }

        curl_close($_curl);

        return $result;
    }


    protected function curl($_url)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $_url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_HTTP09_ALLOWED, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        $res = curl_exec($ch);

        curl_close($ch);

        return $res;
    }
}


